# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import time
import re


requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告


"""
bilibili弹幕 1.数字（av数字）2.BV...
主要查找cid值
https://www.bilibili.com/video/av67946325
https://comment.bilibili.com/弹幕id.xml
https://api.bilibili.com/x/v1/dm/list.so?oid=弹幕id
"""

class DanMu():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        self.cookie = cookiejar.CookieJar()
        # ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        self.headers = {
            # "User-Agent": ua.random
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "Cookie": "CURRENT_FNVAL=16; bsource=seo_baidu; _uuid=7B67FCEF-3209-FD7B-C883-81E1251EDFC694073infoc; buvid3=4CFB4EE6-D08D-4CE6-8A3B-E8BBCC17BB2853948infoc; sid=4q4zpomr; rpdid=|(k||JmYRuuk0J'ulmJRJk~u)",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
        }

    def get_contents(self, id):
        if id.isdigit() == True:
            url = f"https://www.bilibili.com/video/av{id}"
        else:
            url = f"https://www.bilibili.com/video/{id}"
        html = HttpUtils.do_request("GET", url, self.headers, "")
        # 获取弹幕ID
        match_rule = r'cid=(.*?)&aid'
        oid = re.search(match_rule, html.text).group().replace('cid=', '').replace('&aid', '')
        print('oid='+oid)
        # oid = "186803402"
        xml_url = 'https://api.bilibili.com/x/v1/dm/list.so?oid='+oid
        html_xml = HttpUtils.do_request("GET", xml_url, self.headers, "")
        roots = etree.HTML(html_xml.content)
        # for r in roots.xpath('//d/text()'):
        for d in roots.xpath('//d'):
            dict_data = dict()
            dict_data['txt'] = d.xpath('./text()')[0]
            ctime = d.xpath('./@p')[0].split(",")[4]
            dict_data['ctime'] = datetime.fromtimestamp(int(ctime)).strftime("%Y-%m-%d %H:%M:%S")

            print(str(dict_data))


if __name__ == '__main__':
    danmu = DanMu()
    # danmu.get_contents("67946325")
    # danmu.get_contents("95603575")
    danmu.get_contents("BV1fV411k7T2")
